<template lang="pug">
data-page(
  v-bind="pageParams"
)
  mt-table(
    v-bind="tableProps"
  )
  sampleTrajectory(v-model="trajectoryShow" :selectionRow="specimenRow")
</template>

<script setup lang="ts">
import {
  type FormItemProps,
  type IAction,
  type DataPageProps,
  type TableProps,
  useNotify,
  type Action,
} from "@scmt/common-components";
import {
  type ApiBasedOptions,
  type QueryPagination,
  useApi,
} from "@scmt/core-api";
import { type SpecimenQueryParams } from "@scmt/api-lis-specimen";
import sampleTrajectory from "../../components/sampleTrajectory.vue";
import {
  specimenColumns,
  ESpeimenTableColumnKey,
  ESpecimenStatus,
} from "@scmt/api-common";
import { useRequest } from "@scmt/common-hooks";

const $api = useApi();
const $notify = useNotify();
const queryPramas = reactive<SpecimenQueryParams>({
  outward: 1,
  isInspection: 5,
  sendInspectionStartDate: "",
  sendInspectionEndDate: "",
  get _tempDate() {
    return [this.sendInspectionStartDate, this.sendInspectionEndDate];
  },
  set _tempDate(val) {
    [this.sendInspectionStartDate, this.sendInspectionEndDate] = val || [
      "",
      "",
    ];
  },
  pageNum: 1,
  pageSize: 20,
});
const trajectoryShow = ref(false);
const specimenRow = ref({});

const selectionRow = ref([]);
import { useUtils } from "@scmt/lib-utils";
import { type PatientEntity } from "@scmt/api-patient";
const patients = ref<ApiBasedOptions<PatientEntity>>([]);

const { request, data, loadingMap } = useRequest({
  tableData: (q: any) => {
    const { _tempDate, ...params } = Object.assign({}, queryPramas, q);
    return $api.lis.specimen.getSpecimenPageList(params);
  },
  batchGenerateBarcode: (q: any) => {
    return $api.lis.specimen.batchGenerateBarcode(q).then(() => {
      $notify.success("修改成功");
      request("tableData");
    });
  },
  listAsOptions: () => {
    return $api.lis.specimen.category.listAsOptions();
  },
  tubelistAsOptions: () => {
    return $api.lis.tube.listAsOptions();
  },
  patients: async (keyword: string) => {
    if (!keyword && patients.value.length) {
      return patients.value;
    }

    return $api.patient.listAsOptions({ keyword });
  },
  listOffOptions: () => {
    return $api.upms.org.listAsOptions();
  },
});

onMounted(() => {
  request("tableData");
  request("listAsOptions");
  request("tubelistAsOptions");
  request("listOffOptions");
});

const pageParams = computed<DataPageProps>(() => {
  const queryFields: FormItemProps[] = [
    {
      prop: "outpatientNumber",
      label: "业务编号",
    },
    {
      prop: "patientName",
      label: "患者姓名",
    },
    {
      prop: "barcode",
      label: "标本条码",
    },
    {
      prop: "source",
      label: "业务来源",
      as: "select",
      options: {
        loadMethod: () => $api.dict.item.listAsOptions("patient-type"),
      },
    },
    // {
    //   prop: "today",
    //   label: "是否当天",
    //   as: "checkbox",
    //   span: 2,
    //   options: {
    //     loadMethod: () => {
    //       return [
    //         {
    //           label: "是",
    //           value: true,
    //         },
    //       ];
    //     },
    //   },
    // },
    {
      prop: "billingDepartment",
      label: "开单科室",
      as: "select",
      options: {
        render: "office-table",
        loadMethod: $api.upms.org.listAsOptions,
      },
    },
    {
      prop: "specimenTypeId",
      label: "标本类型",
      as: "select",
      options: {
        filterable: true,
        loadMethod: () => {
          return $api.lis.specimen.category.listAsOptions();
        },
      },
    },
    {
      prop: "_tempDate",
      label: "送检时间",
      as: "date",
      options: {
        type: "daterange",
      },
      span: 6,
    },
  ];
  const headerActions: Action[] = [
    // {
    //   label: "结果同步",
    //   event: "sampleSubmission",
    //   type: "primary",
    // },
  ];

  const dataPageProps: DataPageProps = {
    loading: loadingMap.tableData,
    queryModel: queryPramas,
    queryFields,
    onQuery: () => request("tableData"),
    onAct: onPageActions,
    actions: headerActions,
    columns: 6,
    flex: true,
  };

  return dataPageProps;
});

const tableProps = computed(() => {
  const { tableData } = toRefs(data);

  const tableProps: TableProps = {
    loading: loadingMap.tableData,
    data: tableData.value?.items,
    pagination: tableData.value?.pagination,
    columns: [
      {
        type: "selection",
        label: "序号",
        width: "60px",
      },
      {
        prop: "batchNumber",
        label: "批次号",
        width: 170,
      },
      {
        prop: "outwardOrgName",
        tooltip: true,
        label: "外送机构",
        minWidth: 120,
      },
      {
        prop: "outward",
        tooltip: true,
        label: "送检类型",
        minWidth: 120,
        render: ({ row }) => {
          if (row.outward == 1) {
            return h("div", "外送");
          } else {
            return h("div", "否");
          }
        },
      },
      specimenColumns[ESpeimenTableColumnKey.Source],
      specimenColumns[ESpeimenTableColumnKey.OutpatientNumber],
      specimenColumns[ESpeimenTableColumnKey.PatientName],
      specimenColumns[ESpeimenTableColumnKey.Sex],
      specimenColumns[ESpeimenTableColumnKey.Age],
      specimenColumns[ESpeimenTableColumnKey.ApplicationProject],
      specimenColumns[ESpeimenTableColumnKey.SpecimenTypeId],
      specimenColumns[ESpeimenTableColumnKey.Barcode],
      specimenColumns[ESpeimenTableColumnKey.State],
      specimenColumns[ESpeimenTableColumnKey.BillingDepartment],
      specimenColumns[ESpeimenTableColumnKey.BillingDoctor],
      specimenColumns[ESpeimenTableColumnKey.BillingTime],

      {
        prop: "collectionTime",
        label: "采集时间",
        format: "datetime",
      },
      {
        prop: "collectionName",
        label: "采集人",
        tooltip: true,
      },
      specimenColumns[ESpeimenTableColumnKey.Urgent],
      {
        label: "操作",
        fixed: "right",
        actions: [
          {
            label: "标本轨迹",
            event: "check",
            type: "primary",
          },
          {
            label: "修改状态",
            event: "updateState",
            type: "primary",
          },
        ],
      },
    ],
    onAct: onPageActions,
    onPaginate: (pagination: QueryPagination) =>
      request("tableData", pagination),
    onSelectionChange: (selection: any) => {
      selectionRow.value = selection;
    },
    highlightCurrentRow: true,
  };
  return tableProps;
});

const onPageActions = (action: IAction, model?: any) => {
  switch (action.event) {
    case "check":
      specimenRow.value = {};
      specimenRow.value = model;
      trajectoryShow.value = true;
      break;
    case "updateState":
      let specimenIdData = [].concat(model).map((item) => {
        return item.id;
      });
      request("batchGenerateBarcode", {
        specimenList: specimenIdData,
        status: ESpecimenStatus.Receipt,
      });
      break;
  }
};
//监听设备选择改变
watch(
  () => queryPramas.outpatientNumber,
  (item) => {
    request("tableData");
  },
  {
    immediate: true,
  }
);
</script>

<style lang="less" scoped></style>
